package org.lqk.pool.zk;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class GenericSocketConnectionPool implements SocketConnectionPool, InitializingBean,DisposableBean {

	private SocketConnectionConfig socketConnectionConfig;
	// 连接池
	private GenericObjectPool<SocketConnection> objectPool;
	
	private ServerAddressProvider serverAddressProvider;

	@Override
	public SocketConnection borrowSocketConnection() throws Exception {
		return objectPool.borrowObject();
	}

	@Override
	public void returnSocketConnection(SocketConnection connection) {
		objectPool.returnObject(connection);

	}

	@Override
	public void afterPropertiesSet() throws Exception {
		PooledSocketConnectionFactory connectionFactory = new PooledSocketConnectionFactory(socketConnectionConfig,serverAddressProvider);
		objectPool = new GenericObjectPool<SocketConnection>(connectionFactory);
	}

	public SocketConnectionConfig getSocketConnectionConfig() {
		return socketConnectionConfig;
	}

	public void setSocketConnectionConfig(SocketConnectionConfig socketConnectionConfig) {
		this.socketConnectionConfig = socketConnectionConfig;
	}

	@Override
	public void destroy() throws Exception {
		objectPool.close();
		
	}

	public ServerAddressProvider getServerAddressProvider() {
		return serverAddressProvider;
	}

	public void setServerAddressProvider(ServerAddressProvider serverAddressProvider) {
		this.serverAddressProvider = serverAddressProvider;
	}
	
	

}
